<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :minHeight="500" :title="getTitle" width="1000px" destroy-on-close>
    <Tabs v-model:activeKey="activeKey" :tabBarGutter="5" :tabBarStyle="state.tabBarStyle" tab-position="left">
      <TabPane tab="通过链接邀请" key="fromLink" forceRender v-if="state.inviteWay === 'fromLink'">
        <InviteUserByLink :invite="state.oldInvite" ref="inviteLinkRef" @change="handleLinkChange" />
      </TabPane>
      <TabPane tab="添加平台用户" key="fromExistUser" forceRender>
        <BasicTable @register="registerTable" :rowSelection="rowSelection" style="padding: 5px">
          <template #form-addUser="{ model, field }">
            <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
          </template>
        </BasicTable>
      </TabPane>
    </Tabs>

    <template #footer>
      <Button type="primary" v-if="activeKey === 'fromExistUser'" @click="handleSubmit">
        {{ state.inviteWay === "link" ? "添加到至企业" : "确定" }}
      </Button>
      <Button type="primary" v-if="activeKey === 'fromLink' && !state.oldInvite" @click="handleSubmit"> 创建并复制链接 </Button>
      <Button type="primary" v-if="activeKey === 'fromLink' && state.oldInvite" @click="handleSubmit"> 复制链接 </Button>
    </template>
  </BasicModal>
  <UserForm @register="registerDrawer" @success="reload" />
</template>
<script lang="ts" setup>
  import { ref, unref, toRaw, reactive, computed } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicTable, useTable } from "/@/components/Table"
  import { Tabs, TabPane, Button } from "ant-design-vue"
  import { columns, searchUserFormSchema } from "./user.data"
  import InviteUserByLink from "./components/InviteUserByLink.vue"
  import { useDrawer } from "/@/components/Drawer"
  import { list as listUser } from "../user/user.api"
  import { listTenantUser, getUserInvite } from "./user.api"
  import UserForm from "./components/UserForm.vue"
  // 声明Emits
  const emit = defineEmits(["select", "register"])
  const checkedKeys = ref<Array<string | number>>([])
  const activeKey = ref("fromLink")
  const inviteLinkRef = ref<any>()
  const state = reactive({
    inviteWay: "fromExistUser",
    // 是否为平台用户, 会查询所有用户
    selectPlatformUser: false,
    // 是否单选表格数据
    singleSelect: false,
    oldInvite: undefined,
    tabBarStyle: {
      width: "130px",
      marginLeft: "-20px",
      minHeight: "500px",
    },
  })

  const handleLinkChange = (userInvite) => (state.oldInvite = userInvite)

  const listData = (param) => {
    if (!state.selectPlatformUser) {
      return listTenantUser(param)
    } else {
      return listUser(param)
    }
  }

  const [registerDrawer, { openDrawer }] = useDrawer()

  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys }] = useTable({
    api: listData,
    rowKey: "id",
    immediate: false,
    columns: columns,
    formConfig: {
      labelWidth: 70,
      schemas: searchUserFormSchema,
      baseRowStyle: { maxHeight: "20px", marginBottom: "20px" },
      autoSubmitOnEnter: true,
      showActionButtonGroup: false,
    },
    striped: true,
    useSearchForm: true,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    canResize: false,
  })

  const rowSelection = {
    type: "radio", // 为 radio 是单选
    columnWidth: 50,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  }

  const getTitle = computed(() => (state.inviteWay === "fromLink" ? "邀请企业成员" : "选择用户"))

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.inviteWay = data?.inviteWay || state.inviteWay
    state.singleSelect = !!data?.singleSelect
    state.selectPlatformUser = data?.selectPlatformUser || state.selectPlatformUser
    state.oldInvite = await getUserInvite({})
    activeKey.value = state.inviteWay && state.inviteWay === "fromLink" ? "fromLink" : "fromExistUser"
    setModalProps({ draggable: false })
    clearSelectedRowKeys()
    reload()
  })

  /**
   * 选择事件
   */
  function onSelectChange(selectedRowKeys: (string | number)[]) {
    checkedKeys.value = selectedRowKeys
  }

  const handleCreate = () => {
    openDrawer(true, {
      isUpdate: false,
      showFooter: true,
    })
  }

  async function handleSubmit() {
    try {
      setModalProps({ loading: true })
      const selectRows = await getSelectRows().filter((e) => checkedKeys.value.includes(e.id))
      setModalProps({ confirmLoading: true })
      const selectUserIds = toRaw(unref(selectRows))
      if (activeKey.value === "fromExistUser" && selectUserIds.length > 0) {
        emit("select", selectUserIds)
        closeModal()
      } else if (activeKey.value === "fromLink") {
        await inviteLinkRef.value.save()
      }
    } finally {
      setModalProps({ loading: false })
    }
  }
</script>
./user.data./user.api./user.api
